/**
 * Author: Shen Yanqiu
 * Date: 2017-12-09
 * Time: 17:40
 *
 */
/* global window */

import modelExtend from 'dva-model-extend';
import { pageModel } from '../common';
import { doCreateOrganization, getCommunity } from './../../services/organization';
import { message } from 'antd';
import { routerTool } from 'utils';

export default modelExtend(pageModel, {
  namespace: 'organization',

  state: {
    community: [],
    department: [],
  },

  subscriptions: {
    setup ({ dispatch, history }) {
      history.listen((location) => {
        if (location.pathname === routerTool.getPathByName("OrganizationAlert")) {
          // dispatch(routerRedux.push({ pathname: '/' }));
        } else if (location.pathname === routerTool.getPathByName("JoinOrganization")) {
          dispatch({
            type: 'getCommunity',
          });
        }
      });
    },
  },

  effects: {
    // 执行创建组织
    *doCreate ({ payload: values }, { call, put }) {
      // console.log(values);
      const { name, scale, paperwork } = values;
      const params = { name, scale, paperwork };
      const createInfo = yield call(doCreateOrganization, params);
      if (!createInfo.success) {
        message.error("创建组织失败，请检查输入是否正确！");
        return;
      }
      message.success("创建组织成功！");
      // 跳转首页
      window.location.href = routerTool.getPathByName("Home");
      // yield put(
      //   routerRedux.push({ pathname: '/' })
      // );
    },

    // 执行加入组织
    *doJoin ({ payload: values }, { call, put }) {
      // console.log(values);
      // // const joinInfo = yield call(doCreateOrganization, values);
      // // if (!joinInfo.success) {
      // //   message.error("加入组织失败！");
      // //   return;
      // // }
      // // message.success("加入组织成功！");
      // // yield put(
      // //   routerRedux.push({ pathname: '/' })
      // // );
    },

    // 服务器获取组织和部门
    *getCommunity ({ payload = {} }, { call, put }) {
      const { data } = yield call(getCommunity);
      yield put({
        type: 'update',
        payload: { community: data.community },
      });
    },
    // 改变组织联动改变部门选项
    *changeCommunity ({ payload: value }, { call, put, select }) {
      const { community } = yield select(_ => _.organization);
      const oneCommunity = community.filter(t => {
        return t.value === value;
      });
      const department = oneCommunity[0].children;
      yield put({
        type: 'update',
        payload: { department },
      });
    },
  },

  reducers: {
    update (state, { payload }) {
      // console.log(payload);
      return { ...state, ...payload };
    },
  },
});
